package com.sbr.seb.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UrlConnector {

	private static final Logger logger = LoggerFactory.getLogger(UrlConnector.class);

	private String login;
	private String password;
	
	private String proxyHost = "172.27.231.250";
	private int proxyPort = 8080;
	private boolean isProxyEnable = false;
	
	public BufferedReader getReader(String url) throws IOException {
		URL tomcatUrl = null;
		Proxy proxy = null;
		if (isProxyEnable) {
			proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
		} else {
			proxy = Proxy.NO_PROXY;
		}
		HttpURLConnection uc = null;
		try {
			System.out.println("url : "+url);
			tomcatUrl = new URL(url);
			uc = (HttpURLConnection)tomcatUrl.openConnection(proxy);
			uc.connect();
		} catch (IOException e) {
			logger.error("Problème de connection "+url);
			throw e;
		}

		// TODO faire un authentificator par instance 
		
		Authenticator.setDefault(new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication (login, password.toCharArray());
			}
		});

// fermer tous ces fluxs ???
		try {
			return new BufferedReader(new InputStreamReader(uc.getInputStream()));
		} catch (IOException e) {
			logger.error("Problème de connection "+url);
			throw e;
		}
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setProxyHost(String proxyHost) {
		this.proxyHost = proxyHost;
	}

	public void setProxyPort(int proxyPort) {
		this.proxyPort = proxyPort;
	}
	
	
	
}
